<template>
  <base-breadcrumb :title="titleName">
    <searchData
      v-show="activeKey === 'audit'"
      :search-data="searchArr"
      @search="search"
    />
    <searchData
      v-show="activeKey === 'business'"
      :search-data="searchBusinessArr"
      @search="handleSearchBusiness"
    />

    <a-card :bordered="false">
      <a-tabs v-model="activeKey">
        <a-tab-pane
          key="audit"
          tab="审批已办"
        >
          <div>
            <div class="pub-table-select-count">
              <a-icon
                type="info-circle"
                theme="twoTone"
              />
              <span style="margin-right: 12px">
                已审批事项：<span class="totalNum">{{ ybTotalSize|| 0 }} 个</span>
              </span>
            </div>

            <!-- <a-table
              ref="table"
              :pagination="false"

              :columns="columns"
              :data-source="tableData"
              row-key="taskId"
            > -->
            <list-table
              ref="table"
              row-key="taskId"
              :columns="columns"
              :request="loadData"
              :alert="true"
            >
              <span
                slot="serial"
                slot-scope="text, record, index"
              >{{ index + 1 }}</span>

              <span
                slot="status"
                slot-scope="text, record"
              >
                <a-badge
                  v-if="record.taskType == 1"
                  :status="record.formData.reject | statusTypeFilterApproval"
                  :text="record.formData.reject | statusFilterApproval"
                />
                <a-badge
                  v-else
                  :status="text | statusTypeFilter"
                  :text="text | statusFilter"
                />
              </span>
              <span
                slot="taskSource"
                slot-scope="text"
              >
                <ellipsis
                  :length="8"
                  tooltip
                >{{ text | taskSourceFilter }}</ellipsis>
              </span>
              <span
                slot="description"
                slot-scope="text"
              >
                <ellipsis
                  :length="8"
                  tooltip
                >{{ text }}</ellipsis>
              </span>
              <template
                slot="action"
                slot-scope="text, record"
              >
                <MoreButton>
                  <a
                    v-if="record.detailUrl"
                    @click="handleToDetail(record)"
                  >查看</a>
                  <a @click="checkAuditDetail(record)">审批信息</a>
                  <!-- 完成审批流程的不显示,审批不通过不显示 -->
                  <template v-if="record.result * 1 == 0 && record.formData.reject == 'false'">
                    <a
                      v-if="record.urge"
                      @click="handleUrge(record)"
                      v-btnPermission="'ma_002_und_03'"
                    >催办</a>
                    <a
                      @click="handleWithdraw(record)"
                      v-if="record.recall"
                      v-btnPermission="'ma_002_has_02'"
                    >撤回</a>
                  </template>
                </MoreButton>
              </template>
            </list-table>
            <!-- <pagination
              v-model="pageNo"
              :total="totalSize"
              :page-size.sync="pageSize"
              @change="handlePageChange"
              @showSizeChange="showSizeChange"
            /> -->
          </div>
        </a-tab-pane>
        <a-tab-pane
          key="business"
          tab="业务已办"
        >
          <BusinessTodo
            ref="BusinessTodo"
            :is-done="true"
            :todo-status="1"
            :search-query="childQuery"
          />
        </a-tab-pane>
      </a-tabs>
    </a-card>
    <!-- 审批详情 -->
    <ApprovalDetails
      :title="'审批意见'"
      :proc-inst-id="childInitData.procInstId"
      :business-id="childInitData.businessId"
      :visible="visibleState.isAudit"
      @cancel="visibleState.isAudit = false"
      @confirm="visibleState.isAudit = false"
    />
  </base-breadcrumb>
</template>

<script>
// import ApprovalDetails from '@/components/approvalDetails'
// 修改为和我发起的一致
import ApprovalDetails from '@/views/matters/meLaunch/approvalDetails'
import { Ellipsis } from '@/components'

import Vue from 'vue'
import { getOrgEmployeeByUser } from '@/api/commons'
import { getProcessNodeList, getDoneTotal } from '@/api/process'
import BusinessTodo from './BusinessTodo.vue'
import { BUSINESS_SOURCE_MAP } from '@/config/businessConfig.js'
import { toAuditDetail } from '@/utils/util'
import { ugre, rollBack } from '@/api/indexPage'
import OrgTreeSelect from '@/components/TreeSelect'

const searchBusinessArr = [
  {
    name: '标题',
    value: 'noticeTitle',
    type: 'input'
  },
  {
    name: '内容',
    value: 'noticeContent',
    type: 'input'
  }
]

const searchArr = [
  // 搜索框
  {
    name: '事项名称',
    value: 'processName',
    type: 'input'
  },
  {
    name: '事项来源',
    value: 'taskSource',
    type: 'select',
    data: Object.keys(BUSINESS_SOURCE_MAP).map((key) => {
      return {
        label: BUSINESS_SOURCE_MAP[key],
        value: key
      }
    })
  },
  {
    name: '节点类型',
    value: 'taskType',
    type: 'select',
    data: [
      {
        label: '审批',
        value: '1'
      },
      {
        label: '处理',
        value: '2'
      },
      {
        label: '会签',
        value: '3'
      }
    ]
  },
  {
    name: '关键信息',
    value: 'keyword',
    type: 'input'
  },
  {
    name: '发起单位',
    valueKey: 'startOrgName',
    type: OrgTreeSelect,
    attrs: {
      isNeedOrgId: true,
      needTags: [],
      checkStrictly: false,
      isQueryProjecDetail: false,
      isShowProjectStatus: true,
      isSearchPage: true
    }
  }
]

const columns = [
  {
    title: '序号',
    width: '65px',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '事项名称',
    dataIndex: 'processName'
  },
  {
    title: '事项来源',
    dataIndex: 'taskSource',
    scopedSlots: { customRender: 'taskSource' }
  },
  {
    title: '发起单位',
    dataIndex: 'startOrgName'
  },
  {
    title: '关键信息',
    dataIndex: 'keyword'
  },
  {
    title: '节点名称',
    dataIndex: 'taskName'
  },
  {
    title: '节点滞留时间',
    dataIndex: 'durationInMillis'
  },
  {
    title: '节点类型',
    dataIndex: 'taskType',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '处理信息',
    dataIndex: 'formData.opinions',
    ellipsis: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  1: { text: '审批', status: 'warning' },
  2: { text: '处理', status: 'processing' },
  3: { text: '签名', status: 'processing' }
}
const statusApproval = {
  false: { text: '审批通过', status: 'success' },
  true: { text: '审批不通过', status: 'warning' }
}

const taskSourceMap = BUSINESS_SOURCE_MAP

export default {
  name: 'DoneTableList',
  components: {
    Ellipsis,
    ApprovalDetails,
    BusinessTodo
  },
  data() {
    return {
      childQuery: {}, // 子级参数
      searchBusinessArr,
      activeKey: 'audit',
      visibleState: {
        isAudit: false
      },
      childInitData: {},
      searchArr,
      columns,
      titleName: '',
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      selectedRowKeys: [],
      selectedRows: [],
      totalDels: {
        auditNum: 0,
        solveNum: 0,
        signNum: 0
      },
      tableData: [],
      totalSize: 1,
      ybTotalSize:0,
      pageNo: 0,
      pageSize: 10,
      usersIds: [],
      isPage: false,
      loadData: (parameter) => {
        if (!this.isPage) return false
        const requestParameters = Object.assign(parameter, this.queryParam, { users: this.usersIds })
        return getProcessNodeList(requestParameters).then((res) => {
          res.data.forEach((d) => {
            if (d.formData) {
              d.formData = JSON.parse(d.formData)
            }
          })
          this.totalSize = res.totalSize
          this.ybTotalSize = res.totalSize
          return res
        })
      }
    }
  },

  created() {
    this.currentUser = Vue.getAcloudProvider().getUserInfo()
    // this.list()
    this.getByEmployeeUser()
    this.getDoneTotal()
    if (sessionStorage.getItem('listTodoActiveKey')){
      this.activeKey = sessionStorage.getItem('listTodoActiveKey');
      sessionStorage.removeItem('listTodoActiveKey')
    }
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    },
    //审批状态
    statusFilterApproval(type) {
      return statusApproval[type].text
    },
    statusTypeFilterApproval(type) {
      console.log(type, 1111)
      return statusApproval[type].status
    },
    taskSourceFilter(type) {
      return taskSourceMap[type]
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows, // 当前行所有数据
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    /**
     * 业务待办搜索
     */
    handleSearchBusiness(val = {}) {
      this.childQuery = {
        ...val
      }
      this.$nextTick(() => {
        this.$refs.BusinessTodo.refreshTable()
      })
    },
    checkAuditDetail(data) {
      this.childInitData = { ...data }
      this.visibleState.isAudit = true
    },
    handleToDetail(data) {
      console.log(data)
      toAuditDetail.call(this, data)
    },

    getByEmployeeUser() {
      getOrgEmployeeByUser(this.currentUser.id).then((res) => {
        if (res.status === 200) {
          const employee = res.data

          if (employee.posts) {
            this.usersIds = employee.posts.map((p) => p.id)
          }
          this.usersIds.push(this.currentUser.id)

          this.isPage = true
          this.$refs.table.refresh(true)
        }
      })
    },

    async getDoneTotal() {
      try {
        const userInfo = Vue.getAcloudProvider().getUserInfo()
        const userList = (userInfo && userInfo.employee && userInfo.employee.posts && userInfo.employee.posts.map((item) => item.id)) || []
        userList.push(userInfo.id)
        const params = {
          users: userList
        }
        const res = await getDoneTotal(params)
        if (res.code === 200) {
          const map = {
            1: 'auditNum',
            2: 'solveNum',
            3: 'signNum'
          }
          const list = res.data || []
          list.forEach((item) => {
            if (map[item.task_type]) {
              this.totalDels[map[item.task_type]] = item.nums || 0
            }
          })
        }
      } catch {}
    },
    list(parameter, callback) {
      const _this = this
      getOrgEmployeeByUser(this.currentUser.id).then((res) => {
        if (res.status === 200) {
          const employee = res.data

          let users = []
          if (employee.posts) {
            users = employee.posts.map((p) => p.id)
          }
          users.push(this.currentUser.id)
          const requestParameters = Object.assign({ pageSize: callback ? _this.totalSize : _this.pageSize, pageNo: _this.pageNo }, parameter, this.queryParam, { users })
          getProcessNodeList(requestParameters).then((res) => {
            res.data.forEach((d) => {
              if (d.formData) {
                d.formData = JSON.parse(d.formData)
              }
            })
            _this.tableData = res.data
            _this.totalSize = res.totalSize
          })
        }
      })
    },
    handlePageChange(pageNo) {
      this.pageNo = pageNo
      this.list()
    },
    showSizeChange(pageNo, pageSize) {
      this.pageNo = 1
      this.pageSize = pageSize
      this.list()
    },
    search(val) {
      this.queryParam = val
      this.$refs.table.refresh(true)
      // this.list()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    /**
     * @description: 撤回
     * @param {object} record 行数据
     * @return {void}
     */
    handleWithdraw(item) {
      this.$confirm({
        content: '确认撤回至本节点？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          const { id: userId } = Vue.getAcloudProvider().getUserInfo()
          return new Promise(async (resolve) => {
            try {
              await rollBack({
                procDefId: item.procDefId,
                procInstId: item.procInstId,
                targetTaskKey: item.taskDefKey
              })
              resolve()
              this.$refs.table.refresh(true)
            } catch (error) {
              console.log(error)
              resolve()
            }
          })
        }
      })
    },
    /**
     * @description: 催办
     * @param {object} record 行数据
     * @return {void}
     */
    handleUrge({ procInstId }) {
      this.$confirm({
        content: '确认催办？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          return new Promise(async (resolve) => {
            try {
              await ugre(procInstId)
              this.$refs.table.refresh(true)
              resolve()
            } catch (error) {
              resolve()
            }
          })
        }
      })
    }
  }
}
</script>


